<template>
  <div class="ctlTask-root">
    <lark-drawer border title="采集任务" title-height="40px" width="420px"  ref="drawer">

      <div class="ctlTask-body">
        <div class="ctlTask-body-head">
          <el-input class="ctlTask-body-head__search" v-model="searchParams.taskName" placeholder="输入任务名称进行搜索">
            <el-button slot="append" icon="el-icon-search" @click="searchBtn"></el-button>
          </el-input>
          <el-button icon="el-icon-plus" class="ctlTask-body-head__add" round @click="addTaskBtn">新增</el-button>
        </div>
        <div class="more-data"></div>


        <div class="ctlTask-list" id="ctlTask-list">

          <line-table :table-header="tableHeaders" :table-data="dataList" @rowClick="rowClick">
            <template v-slot:num="{row}">
              <el-progress :text-inside="true" :color="customColors" :stroke-width="26"
                           :percentage="row.num * 100>100?100:parseFloat((row.num * 100).toFixed(3))"></el-progress>
            </template>
            <template v-slot:operation="{row}">
              <div style="width: 100%;text-align: center">
                <el-dropdown trigger="click">
                  <div class="ctlTask-list-row-operation-btn" style="width:15px;margin-left: 10px">
                    <i class="fa fa-ellipsis-v" aria-hidden="true"></i>
                  </div>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-if="row.state == 0" icon="el-icon-delete" @click.native="deleteBtn(row)">禁用
                    </el-dropdown-item>
                    <el-dropdown-item v-if="row.state == 0" icon="el-icon-edit" @click.native="updateBtn(row)">修改
                    </el-dropdown-item>
                    <el-dropdown-item v-else icon="el-icon-view" @click.native="updateBtn(row)">详情</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>

            </template>
          </line-table>
        </div>


        <div class="ctlTask-pagination">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="pageInfo.total"
            :current-page="pageInfo.pageNum"
            :page-size="pageInfo.pageSize"
            @current-change="pageChange"
          >
          </el-pagination>


        </div>
      </div>
    </lark-drawer>

    <lark-card border :x="300" :y="100" body-height="500px" :body-width="'500px'" v-if="editTaskVisible"
               :hidden="!editTaskVisible"
               @closeAction="editTaskVisible = !editTaskVisible"
               card-title="采集任务详情" draggable
               :radius="false">
      <el-scrollbar>
        <div class="edit-task-body" style="padding: 10px 5px">
          <el-form ref="edit-task-form" :model="editTaskForm" label-width="80px" :rules="rules" v-if="">
            <el-form-item v-show="editTaskForm.id!=null" label="任务状态">
              {{ stateStr }}
            </el-form-item>
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="editTaskForm.taskName" v-if="currentState == 0 || currentState == null"></el-input>
              <div v-else>{{ editTaskForm.taskName }}</div>
            </el-form-item>
            <el-form-item label="采集地点" prop="location">
              <el-input v-model="editTaskForm.location" v-if="currentState == 0|| currentState == null"></el-input>
              <div v-else>{{ editTaskForm.location }}</div>
            </el-form-item>
            <!--            <el-form-item label="采集区域" prop="regionId">-->
            <!--              &lt;!&ndash;              <el-button @click="()=>{}">绘制区域</el-button>&ndash;&gt;-->
            <!--              <el-input v-model="editTaskForm.regionId" v-if="currentState == 0|| currentState == null"></el-input>-->
            <!--              <div v-else>{{ editTaskForm.regionId }}</div>-->
            <!--            </el-form-item>-->
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker v-model="editTaskForm.startDate" v-if="currentState == 0|| currentState == null"
                              value-format="yyyy-MM-dd"></el-date-picker>
              <div v-else>{{ editTaskForm.startDate }}</div>
            </el-form-item>
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="editTaskForm.endDate" v-if="currentState == 0||  currentState == null"
                              value-format="yyyy-MM-dd"></el-date-picker>
              <div v-else>{{ editTaskForm.endDate }}</div>
            </el-form-item>
            <el-form-item label="采集内容" prop="cltData">
              <!--              <el-button @click="()=>{}">绘制区域</el-button>-->
              <el-input v-model="editTaskForm.cltData" v-if="currentState == 0|| currentState == null"></el-input>
              <div v-else>{{ editTaskForm.cltData }}</div>
            </el-form-item>
            <el-form-item label="采集数量" prop="planNum">
              <el-input type="number" v-model="editTaskForm.planNum"
                        v-if="currentState == 0|| currentState == null"></el-input>
              <div v-else>{{ editTaskForm.planNum }}</div>
            </el-form-item>


            <el-form-item label="采集用户" prop="users">
              <div class="u-l-container" v-if="editTaskForm.users.length > 0">
                <el-scrollbar>
                  <el-tag
                    style="margin-right: 5px"
                    v-for="user in editTaskForm.users"
                    :key="user.userName"
                    :closable="currentState == 0||  currentState == null"
                    type="info"
                    @close="userRemove(user)">
                    {{ user.nickName }}
                  </el-tag>
                </el-scrollbar>
              </div>
              <div>
                <el-button v-if="currentState == 0|| currentState == null" size="mini" @click="selectUserBtn">选择用户
                </el-button>
              </div>
            </el-form-item>

          </el-form>
          <div class="edit-task-submit" v-if="currentState == 0|| currentState == null">
            <el-button @click="saveBtn">保存</el-button>
          </div>

          <div class="edit-task-submit" v-else>
            <el-button @click="editTaskVisible = false">关闭</el-button>
          </div>

        </div>
      </el-scrollbar>
    </lark-card>

    <lark-card border card-title="选择采集人" :x="500" :radius="false" v-if="selectUserVisible" :hidden="!selectUserVisible"
               body-width="700px" body-height="550px"
               @closeAction="selectUserVisible = !selectUserVisible" draggable>
      <div class="select-user-body">
        <user-select :can-select-is-ctl="false" v-model="editTaskForm.users"></user-select>
        <div style="width: 100%;text-align: right;padding-right:20px">
          <el-button @click="selectUserVisible = false">确定</el-button>
        </div>

      </div>
    </lark-card>

  </div>
</template>

<script>
  import { reactive, toRefs, onMounted, ref, watch, computed } from '@vue/composition-api'
  import { taskList, addTask, disableTask, editTask, getTask } from '@/api/industry/ctl'
  import loading from '@/utils/loading'
  import userSelect from '@/components/ServiceComponents/userSelect'
  import { Message } from 'element-ui'
  import { baseValidate } from '@/utils/elementValidate'
  import lineTable from '@/components/ServiceComponents/lineTable'

  export default {
    name: 'ctlTask',
    components: {
      userSelect,
      lineTable
    },
    setup(props, content) {
      const tableHeaders = [
        { name: '任务名称', prop: 'taskName', width: '120px' },
        { name: '计划采集量', prop: 'planNum', width: '100px' },
        { name: '采集进度', prop: 'num', width: '100px', type: 'slot' },
        { name: '操作', prop: 'operation', type: 'slot' }
      ]
      let data = reactive({
        tableHeaders,
        customColors: [
          // { color: '#f56c6c', percentage: 20 },
          // { color: '#e6a23c', percentage: 40 },
          // { color: '#6f7ad3', percentage: 60 },
          // { color: '#1989fa', percentage: 80 },
          // { color: '#5cb87a', percentage: 100 }

          { color: 'rgb(45,175,60)', percentage: 20 },
          { color: 'rgb(45,175,60)', percentage: 40 },
          { color: 'rgb(45,175,60)', percentage: 60 },
          { color: 'rgb(45,175,60)', percentage: 80 },
          { color: 'rgb(45,175,60)', percentage: 100 }
        ],
        rules: {
          taskName: [
            { min: 1, max: 30, required: true, name: '任务名称', validator: baseValidate, trigger: 'blur' }
          ],
          startDate: [
            { required: true, message: '任务开始时间不能为空', trigger: 'blur' }
          ],
          endDate: [
            { required: true, message: '任务结束时间不能为空', trigger: 'blur' }
          ],
          regionId: [
            { min: 1, max: 50, required: true, name: '采集区域', validator: baseValidate, trigger: 'blur' }
          ],
          location: [
            { min: 1, max: 50, required: true, name: '采集地点', validator: baseValidate, trigger: 'blur' }
          ],
          planNum: [
            { required: true, message: '计划采集数量不能为空', trigger: 'blur' }
          ],
          cltData: [
            { min: 1, max: 30, required: true, name: '采集内容', validator: baseValidate, trigger: 'blur' }
          ]
        },

        pageInfo: {
          total: 0,
          pageNum: 1,
          pageSize: 7
        },
        searchParams: {
          taskName: ''
        },
        editTaskForm: {
          id: null,
          startDate: null,
          taskName: null,
          endDate: null,
          location: null,
          regionId: null,
          planNum: null,
          cltData: null,
          users: []
        },
        currentState: null,
        editTaskVisible: false,
        selectUserVisible: false,
        dataList: []
      })
      const resetEditTaskForm = () => {
        data.editTaskForm = {
          id: null,
          taskName: null,
          startDate: null,
          endDate: null,
          location: null,
          regionId: null,
          planNum: null,
          cltData: null,
          users: [] //{userId:userName,nickName:nickName}
        }
      }
      const progressFormat = (per) => {
        return per
      }

      let stateStr = computed(() => {
        //  currentState == 1 ? '禁用' : '正常'
        if (data.currentState == 1) {
          return '禁用'
        } else if (data.currentState == 0) {
          return '正常'
        } else {
          return '临时任务'
        }
      })

      const selectUserBtn = () => {
        data.selectUserVisible = true
      }
      const pageChange = async(currentPage) => {
        data.pageInfo.pageNum = currentPage
        await loadListData()
      }

      const loadListData = async() => {
        let load = loading(document.getElementById('ctlTask-list'))
        try {
          let response = await taskList({ ...data.searchParams, ...data.pageInfo })
          data.dataList = response.rows
          data.pageInfo.total = response.total
        } finally {
          load.close()
        }
      }

      const searchBtn = async() => {
        data.pageInfo.pageNum = 1
        await loadListData()
      }

      const rowClick = (item) => {
        content.emit('rowClick', item)
      }
      const addTaskBtn = () => {
        resetEditTaskForm()
        data.currentState = null
        data.editTaskVisible = true
      }
      const updateBtn = async(item) => {
        resetEditTaskForm()
        let response = await getTask(item.id)
        const { data: { id, startDate, endDate, location, regionId, users, taskName, cltData, planNum } } = response
        data.editTaskForm = {
          id, startDate, endDate, location, regionId, taskName, cltData, planNum
        }
        data.currentState = response.data.state
        data.editTaskForm.users = users.map(user => {
          return { userId: user.userId, nickName: user.nickName }
        })
        data.editTaskVisible = true
      }
      const userRemove = (user) => {

        data.editTaskForm.users = data.editTaskForm.users.filter(item => item.userId !== user.userId)

        data.editTaskForm = JSON.parse(JSON.stringify(data.editTaskForm))

      }
      const saveBtn = async() => {

        //  表单校验
        content.refs['edit-task-form'].validate(async(valid) => {
          if (valid) {
            if (data.editTaskForm.users.length == 0) {
              Message.warning('至少选择一个采集人')
              return
            }
            let load = loading(document.getElementById('ctlTask-list'))
            try {
              let requestData = JSON.parse(JSON.stringify(data.editTaskForm))
              if (requestData.id == null) {
                await addTask(requestData)
              } else {
                await editTask(requestData)
              }
              data.pageInfo.pageNum = 1
              await loadListData()
              data.editTaskVisible = false
            } finally {
              load.close()
            }
          }
        })

      }

      const deleteBtn = async(item) => {

        MessageBox.confirm('此操作将禁用该任务, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          let load = loading(document.getElementById('ctlTask-list'))
          try {
            await disableTask(item.id)
            data.pageInfo.pageNum = 1
            await loadListData()
          } finally {
            load.close()
          }
        }).catch(() => {
        })

      }

      onMounted(async() => {
        data.pageInfo.pageNum = 1
        await loadListData()
      })
      return {
        ...toRefs(data),
        addTaskBtn,
        deleteBtn,
        rowClick,
        pageChange,
        searchBtn,
        selectUserBtn,
        userRemove,
        saveBtn,
        updateBtn,
        stateStr,
        progressFormat,
      }
    }
  }
</script>

<style scoped lang="scss">


  $list-row-height: 36px;
  .ctlTask-root {


    .ctlTask-body {
      position: relative;
      padding: 10px 10px 0 10px;
      height: 42vh;

      .ctlTask-pagination {
        height: 35px;
      }

      .ctlTask-list {
        height: calc(42vh - 68px - 35px);
        overflow: hidden;

        .ctlTask-list-row {
          height: $list-row-height;
          line-height: $list-row-height;
          display: flex;
          flex-direction: row;
          border-bottom-style: dashed;
          border-bottom-width: 1px;
          justify-content: space-between;

          &:hover {
            .ctlTask-list-row-hover {
              cursor: pointer;
            }

            border-bottom-style: solid;
          }

          .ctlTask-list-name {
            width: 150px;
            display: flex;
            align-items: center;

            .content-hidden {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .task-name {
              flex-basis: 120px;
            }

            .ctlTask-list-row-icon {
              margin-right: 20px;
              margin-left: 10px;
            }
          }


          .ctlTask-list-row-operation {
            margin-right: 10px;
            margin-left: 10px;
            text-align: center;

            .ctlTask-list-row-operation-btn {
              width: 15px;

              &:hover {
                cursor: pointer;
              }
            }
          }

        }
      }

      .more-data {
        width: 100%;
        text-align: right;
        border-bottom-style: dashed;
        border-bottom-width: 1px;
        padding: 10px;
      }

      .ctlTask-body-head {
        display: flex;
        flex-direction: row;

        .ctlTask-body-head__search {
        }

        .ctlTask-body-head__add {
          margin-left: 10px;
        }

      }
    }


  }
</style>
<style lang="scss">
  .edit-task-body {
    position: relative;
    height: 490px;

    .u-l-container {
      height: 50px;
      max-height: 50px;
    }

    .edit-task-submit {
      position: absolute;
      right: 20px;
      bottom: 10px;
    }
  }

  .select-user-body {
    height: 500px;
  }

  .ctlTask-root {
    .ctlTask-body-head {
      .ctlTask-body-head__search {
      }

      .el-button.el-button--default.ctlTask-body-head__add.el-button--medium {
        padding: 10px 10px
      }

    }
  }
</style>
